package cn.itsource.ymcc.mq;

import cn.itsource.ymcc.constant.MQConstants;
import cn.itsource.ymcc.service.IPayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RocketMQTransactionListener(
        txProducerGroup= MQConstants.TX_PAY_NOTIFY_PRODUCE_GROUP
)
public class NotifyPayMessageTxLinsterner implements RocketMQLocalTransactionListener {

    @Autowired
    private IPayOrderService payOrderService;


    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object obj) {
        log.info("执行本地事务！");
        try {
            if (message == null || obj == null) {
                log.info("执行本地事务,监听异常！{}，{}", message, obj);
                return RocketMQLocalTransactionState.ROLLBACK;
            }

            String orderNo = (String) obj;

            //4. 修改支付单状态
            //5. 保存支付流水
            payOrderService.updatePayOrderAndSaveFlow(orderNo);
        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("执行本地事务的执行状态！");
        return null;
    }
}
